from wtforms import StringField, Form, BooleanField
from wtforms.validators import DataRequired, Length, EqualTo, Email, Regexp, ValidationError

from app.model.user import User


class LoginForm(Form):
    email = StringField(validators=[DataRequired(), Email('不是合法的Email地址')])
    admin = StringField(validators=[DataRequired()])
    password = StringField(
        validators=[
            DataRequired(),
            Regexp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$', message='密码由8-16位字母数字组成')
        ]
    )

    def validate_admin(self, field):
        value = field.data
        self.admin.data = True if value == '是' else False


class RegisterForm(Form):
    email = StringField(validators=[DataRequired(), Email('请填写合法的Email地址')])
    password = StringField(
        validators=[
            DataRequired(),
            Regexp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$', message='密码由8-16位字母数字组成')
        ]
    )
    verify_password = StringField(validators=[EqualTo('password', message='请验证你的密码保证两次输入相同')])
    realname = StringField(validators=[DataRequired('请填写真实姓名用于收取快递'), Length(2, 5, message='请填写真实姓名用于收取快递')])
    address = StringField(validators=[DataRequired('请填写收货地址'), Length(5, 20, message='请填写收货地址')])
    tel = StringField(validators=[DataRequired('请填写联系电话'), Length(11, 11, message='请填写11位电话号码用于接收快递')])

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError('邮箱已被注册')
